import time
from selenium.webdriver.common.by import By
from taobao_check.tools import click_by_js
from .base import BaseBrush


class SiJiYou(BaseBrush):
    login_url = "https://sijixiu.lhy2002.com/business/#/login"
    index_url = "https://sijixiu.lhy2002.com/business/#/taskCenter/publishTask"
    check_url = "https://sijixiu.lhy2002.com/business/#/taskCenter/advanceTask"

    def __init__(self, config, tab):
        super().__init__("四季柚", "sijiyou", config, tab)

    def login(self):
        if self.browser.current_url != self.login_url:
            self.browser.get(self.login_url)

        self.enter_text((By.CSS_SELECTOR, "input[type='text']"), self.username)
        self.enter_text((By.CSS_SELECTOR, "input[type='password']"), self.password)
        self.click_button((By.CSS_SELECTOR, "button[type='button']"))

        while self.browser.current_url != self.index_url:
            time.sleep(0.1)

        self.browser.get(self.check_url)

    def check_user(self):
        div = self.find_elements((By.CSS_SELECTOR, "div.jack-tabs-item"))[1]
        click_by_js(self.browser, div)

        try:
            buy_info = self.find_element((By.CSS_SELECTOR, "div.buy_info"))
        except Exception as e:
            self.print_log("没有买号.", debug=True)
            self.sleep(self.refresh_time)
            return False

        username = buy_info.get_attribute('textContent').split("验号")[0].strip()
        self.print_log(f"当前待验买号为：【{username}】")

        start = time.time()
        result = self.check.check_user(username, self.print_log)
        self.print_log(f"验号结果为: {'通过' if result else '不通过'}. 用时: {time.time() - start:.2f}s")

        div = self.find_element((By.CSS_SELECTOR, "div.edit_info"))
        buttons = div.find_elements_by_tag_name("p")
        change_btn, pass_btn = buttons[1], buttons[2]

        if not result:
            click_by_js(self.browser, change_btn)
        else:
            click_by_js(self.browser, pass_btn)

        ok_btn = self.find_elements((By.CSS_SELECTOR, "div.el-message-box__btns>button"))[1]
        click_by_js(self.browser, ok_btn)
        self.sleep(2)
        return True
